/**
 * Copyright (C) 2012 Oleg Anastassov <o.anastasov@gmail.com>
 *
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package kz.kstu.ent.app.util.locator;

import kz.kstu.ent.business.client.config.Configuration;
import kz.kstu.ent.business.common.exception.ServerNotFoundException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.util.Properties;

/**
 * @author Oleg Anastassov
 *         created: 28.07.11 21:23
 */
public class EJBRemoteServiceLocator extends AbstractServiceLocator {

    private static final String REMOTE_BEAN_POSTFIX = "Remote";
    private static final String CONTEXT_FACTORY = "org.openejb.client.RemoteInitialContextFactory";
    private static final String PROVIDER_PREFIX = "ejbd://";

    private InitialContext initialContext;

    public EJBRemoteServiceLocator() {
    }

    @Override
    protected String getServiceFullName(String serviceName) {
        return serviceName + REMOTE_BEAN_POSTFIX;
    }

    @Override
    protected InitialContext getInitialContext() {
        if (initialContext == null) {
            String host = Configuration.getInstance().getParameter(Configuration.HOST_PARAM_NAME);
            String port = Configuration.getInstance().getParameter(Configuration.PORT_PARAM_NAME);
            String providerUrl = PROVIDER_PREFIX + host + ":" + port;
            Properties properties = new Properties();
            properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, CONTEXT_FACTORY);
            properties.setProperty(Context.PROVIDER_URL, providerUrl);
            try {
                initialContext = new InitialContext(properties);
            } catch (NamingException e) {
                throw new ServerNotFoundException(e.getMessage(), e);
            }
        }
        return initialContext;
    }
}
